package com.android.videotest.music.base;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.media.MediaBrowserCompat;
import android.support.v4.media.MediaMetadataCompat;
import android.support.v4.media.session.MediaControllerCompat;
import android.support.v4.media.session.PlaybackStateCompat;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.media.MediaBrowserServiceCompat;

import com.android.videotest.music.MediaBrowserHelper;
import com.android.videotest.music.MusicService;

import java.util.List;

public abstract class BaseMusicDialog extends Dialog {

    protected MediaBrowserHelper mMediaBrowserHelper;

    public BaseMusicDialog(@NonNull Context context) {
        super(context);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mMediaBrowserHelper = new BaseMusicDialog.MediaBrowserConnection(getContext(), MusicService.class);
        mMediaBrowserHelper.registerCallback(new BaseMusicDialog.MediaBrowserListener());
    }

    @Override
    public void onStart() {
        super.onStart();
        mMediaBrowserHelper.onStart();
    }

    @Override
    public void onStop() {
        super.onStop();
        mMediaBrowserHelper.onStop();
    }

    private class MediaBrowserConnection extends MediaBrowserHelper {
        public MediaBrowserConnection(Context context, Class<? extends MediaBrowserServiceCompat> serviceClass) {
            super(context, serviceClass);
        }

        @Override
        protected void onConnected(@NonNull MediaControllerCompat mediaController) {
            BaseMusicDialog.this.onConnected(mediaController);
        }

        @Override
        protected void onChildrenLoaded(@NonNull String parentId, @NonNull List<MediaBrowserCompat.MediaItem> children) {
            BaseMusicDialog.this.onChildrenLoaded(parentId, children);
        }

        @Override
        protected void onDisconnected() {
            BaseMusicDialog.this.onDisconnected();
        }
    }

    protected abstract void onConnected(@NonNull MediaControllerCompat mediaController);

    protected abstract void onChildrenLoaded(@NonNull String parentId, @NonNull List<MediaBrowserCompat.MediaItem> children);

    protected abstract void onDisconnected();

    private class MediaBrowserListener extends MediaControllerCompat.Callback {
        @Override
        public void onPlaybackStateChanged(PlaybackStateCompat state) {
            BaseMusicDialog.this.onPlaybackStateChanged(state);
        }

        @Override
        public void onMetadataChanged(MediaMetadataCompat metadata) {
            BaseMusicDialog.this.onMetadataChanged(metadata);
        }
    }

    protected abstract void onPlaybackStateChanged(PlaybackStateCompat state);

    protected abstract void onMetadataChanged(MediaMetadataCompat metadata);
}
